import os
import cv2
from matplotlib import pyplot as plt
from src.图片预处理 import image_preprocessing
from src.检测条纹区域 import auto_dense_stripe_roi, manual_box_selection
from src.逆变换 import brightest_symmetric_spot
from 测量比例尺 import detect_scale_bar


def batch(folder,
          detect_bar=True,
          auto_roi=True,
          preprocess=True,
          fft2_r=True,
          man_roi=True
          ):
    """批量处理"""
    for image in os.listdir(folder):
        if image.endswith('.tif'):
            print(f"====================处理图像文件: {image}===================")
            img_path = os.path.join(folder, image)
            img = cv2.imread(img_path, 0)
            if img is None:
                print(f"错误:无法加载图像，请检查路径:{img_path}")
                exit()
            # 处理
            if detect_bar:
                # 测量比例尺，减少比例尺干扰
                img, _1, _2 = detect_scale_bar(gray_img=img, img_type=2048)
            if preprocess:
                img, enhanced = image_preprocessing(img=img)
                if auto_roi:
                    # 检测条纹区域
                    roi_img, roi = auto_dense_stripe_roi(enhanced)
                    if roi is None:
                        print('未检测到条纹区域')
                        exit()
                    print('自动 ROI:', roi)
                    if fft2_r:
                        brightest_symmetric_spot(roi_img)
                elif man_roi:
                    # 手动选择条纹区域
                    roi_img, roi = manual_box_selection(enhanced)
                    if roi is None:
                        print('未选择条纹区域')
                        exit()
                    print('自动 ROI:', roi)
                    if fft2_r:
                        brightest_symmetric_spot(roi_img)


if __name__ == "__main__":
    folder_path = "../img/new/"
    plt.rc('font', family='Microsoft YaHei')
    batch(folder_path, detect_bar=True, auto_roi=True, preprocess=True, fft2_r=True, man_roi=False)
